package cn.range.filedownserver;

import java.io.IOException;
import java.io.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileDownServlet
 */
@WebServlet("/FileDownServlet")
public class FileDownServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final int DEFAULT_BUFFER_SIZE = 4096;
	private String encoding = DEFAULT_ENCODING;
	private int bufferSize = DEFAULT_BUFFER_SIZE;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownServlet() {
        super();
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		String paramEncoding = config.getInitParameter("encoding");
		if(paramEncoding != null && paramEncoding.trim().length() > 0){
			encoding = paramEncoding.trim();
		}
		
		String paramSize = config.getInitParameter("bufferSize");
		if(paramSize != null && paramSize.matches("^[0-9]+$")){
			bufferSize = Integer.parseInt(paramSize);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 
		doPost(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*Search for file*/
		File file = new File(getServletContext().getRealPath("/") + request.getServletPath());
		if(!file.exists()){
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		/*Set content of response*/
		response.setContentType("application/x-msdownload; charset=" + encoding);
		response.addHeader("content-type", "application/x-msdownload");
		response.addHeader("content-disposition", "attachment; filename=" + response.encodeURL(file.getName()));
		response.setContentLength((int) file.length());
		
		/*Output*/
		InputStream in = new FileInputStream(file);
		OutputStream out = response.getOutputStream();
		
		try{
			int length = 0;
			byte[] buffer = new byte[bufferSize];
			while((length = in.read(buffer)) != -1){
				out.write(buffer, 0, length);
			}
			out.flush();
		}finally{
			if(in != null)
				in.close();
		}
	}

}
